<template>
  <div>
    <headTop></headTop>
    <el-card>
      <searchView :formOptions="searchFormData" v-on:onSearch="searchHandle"/>
      <el-button type="info" @click="selecetMutily()" v-if="isSelected == false"
        >批量选择</el-button
      >
      <el-button type="info" @click="selecetMutily()" v-else
        >取消选择</el-button
      >

      <el-button
        type="warning"
        @click="deleteMutily()"
        :disabled="!isDeleteEnable"
        >批量删除</el-button
      >
      <el-button type="primary" icon="el-icon-plus" @click="addNewProduct()"
        >添加产品</el-button
      >

      <div style="margin-top: 10px">
        <el-table
          :data="productList"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%"
          ref="staffTable"
        >
          <el-table-column v-if="isSelected" type="selection" width="55">
          </el-table-column>
          <el-table-column type="index" width="50" label="序号" align="center">
          </el-table-column>
          <el-table-column
            prop="product_no"
            label="编号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="product_name"
            label="品名"
            align="center"
          ></el-table-column>
          <el-table-column prop="images" label="附件" align="center">
            <template slot-scope="scope">
               <el-image
      style="width: 80px; height: 80px"
      :src="scope.row.images.split(',')[0]"    
      fit="fill"
      :preview-src-list="scope.row.images.split(',')"
      >
       <div slot="error" class="image-slot">
        <i class="el-icon-picture-outline"></i>
      </div>
      </el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="categray.name"
            label="类别"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="unit.name"
            label="单位"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="cust.company"
            label="客户公司"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            align="center"
          ></el-table-column>
         
          <el-table-column label="状态"
                      prop="status"
                       align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 1">启用</el-tag>
              <el-tag type="danger" v-else>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                @click="editHandle(scope.row)"
                circle
              ></el-button>
              <el-button
                type="danger"
                @click="deleteHandle(scope.row)"
                icon="el-icon-delete"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="page-bottom"
          :page-size="currentPageSize"
          layout="prev, pager, next, jumper, ->, total"
          :total="totalCount"
          :current-page.sync="currentPage"
          @current-change="currentPageChange"
        >
        </el-pagination>
      </div>
    </el-card>
  
     <el-dialog
      :title="isEdit ? '修改信息' : '添加产品'"
      :visible.sync="isAddShow"
      :before-close="closehandle"
    >
         <insert
        :dataForm="currentItem"
        ref="productForm"
        v-on:updateSuccess="updateSuccess"
      ></insert>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closehandle">取 消</el-button>
        <el-button type="primary" @click="handleClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import search from "@/components/searchView";
import headTop from "@/components/headTop";
import insert from "./insert.vue";
import atoast from "@/components/AToast";
import searchView from "@/components/searchView";
import { formatDate } from "@/utils/mUtils";
import {
  productlist,
  productdelete
} from "@/api/product";
import {
  getCustList
} from "@/api/getData"
import moment from "moment";
export default {
  inject: ["reload"],
  data() {
    return {
      url: "../../assets/img/luosi.jpg",
      direction: "rtl",
      productList: [],
      totalCount: 0,
      currentPage: 0,
      currentPageSize: 10,
      pageCount: 1,
      currentItem: {},
      isAddShow: false,
      isEdit: false,
      isSelected: false,
      isDeleteEnable: false,
      multiSelectes: [],
      custs: [],
      searchFormData:[
        {
          label: '品名',
          prop: 'product_name',
          element: 'el-input'
        },
         {
          label: '编号',
          prop: 'product_no',
          element: 'el-input'
        },
         {
          label: '公司名称',
          prop: 'company',
          element: 'el-input'
         },
        {
          label: '状态',
          prop: 'status',
          element: 'el-select',
          options:[
              { label: '禁用', value: 0 },
             { label: '启用', value: 1 }
          ]
        }
      ],
    };
  },
  created(){
     this.getProductList();
      getCustList().then((res)=>{
        if (res.code == 200){
            this.custs = res.data.data;
        }else{
          this.$message(res.msg);
        }
      });
  },
  mounted() {

      },

  components: {
    search,
    headTop,
    insert,
    searchView,
  },
  methods: {
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD");
    },
    selecetMutily() {
      this.isSelected = !this.isSelected;
      this.$refs.staffTable.clearSelection();
    },
    handleSelectionChange(val) {
      this.isDeleteEnable = val.length;
      this.multiSelectes = val;
    },
    deleteMutily() {
      var ids = [];
      this.multiSelectes.forEach((element) => {
        ids.push(element.product_id);
      });
      var idPas = ids.join(",");
      if (!idPas.length) {
        return;
      }
      this.$confirm("是否批量删除已选择的内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.removeProduct(idPas);
          this.isSelected = false;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
    searchHandle(data){
      this.getProductList(data);
    },
    async getProductList(data = null) {
      try {
      var params = {};
        if(data != null){
          params = data;
          }
          params['page'] = this.currentPage;
          params['pageSize'] = 10;
        const result = await productlist(params);
        if (result.code == 200) {
          console.log(result);
          var rlist = result.data.data;
          this.productList = rlist;
          this.totalCount = result.data.total;
          this.currentPageSize = result.data.page_size;
          this.pageCount = result.data.pages;
          this.currentPage = result.data.current_page;
        }
      } catch (error) {}
    },
   
    handleClick() {
            this.$refs.productForm.onSubmit(this.isEdit);

    },
    closehandle(data) {
      this.currentItem = Object.assign({}, data);
      this.$refs["productForm"].resetFields();
      this.isAddShow = false;
    },
    currentPageChange(val) {
      this.currentPage = val;
      this.getProductList();
    },
    updateSuccess() {
      this.$message('操作成功');
      this.currentItem = Object.assign({}, {});
      this.$refs["productForm"].resetFields();
      this.isAddShow = false;
      this.getProductList();
    },

    deleteHandle(data) {
      this.$confirm("是否删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.removeProduct(data.product_id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editHandle(data) {
      this.isEdit = true;
      this.isAddShow = true;
      data.imageFiles = data.images.split(',').map((ele)=>{
        var str=new RegExp("http");
        if (str.test(ele)) {
        return {url:ele}
        }
      });
      let c = JSON.parse(JSON.stringify(data));
      this.currentItem = c;
    },
    addNewProduct() {
      this.currentItem = {};
      this.isAddShow = true;
      this.isEdit = false;
    },
    async removeProduct(data) {
      try {
        let params = {
          product_id: data,
        };
        console.log(params);
        const result = await productdelete(params);
        if (result.code == 200) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getProductList();
        }
      } catch (error) {
        this.$message({
          type: "error",
          message: "删除失败!",
        });
      }
    },
  },
};
</script>

<style lang="less">
@import "../../style/normal.less";

.buttons-content {
  margin: 10px;
  border-radius: 8px;
  display: inline-flex;
  align-items: center;
}
.page-bottom {
  margin: 10px;
}
</style>
